<script setup lang="ts">
import { ArrowRight } from "@element-plus/icons-vue";
import axios, { isAxiosError } from "axios";
import { ElMessage } from "element-plus";
import { computed, onMounted, ref } from "vue";
import { useRoute } from "vue-router";
import { useLogging } from "../stores/logging";
import type { Book } from "../types/Book";
import type { BorrowRecord } from "../types/BorrowRecord";
import type { FavoriteRecord } from "../types/FavoriteRecord";
import { BusinessStatusCode, type ResultContext } from "../types/ResultContext";

const route = useRoute();
const book = ref<Book>();
const categoryName = ref("");
const dialogVisible = ref(false);
const returnDialogVisible = ref(false);
const now = ref(new Date());
const logging = useLogging();
const borrowRecord = ref<BorrowRecord>();
const favoriteRecord = ref<FavoriteRecord>();
const isLoading = ref(false);

// 封装请求函数，接受 number 类型 ID
const fetchBook = async (bookId: number): Promise<void> => {
  try {
    const response = await axios.get<ResultContext<Book>>(
      `http://localhost:8080/api/books/${bookId}`,
    );
    book.value = response.data.data;
  } catch (error) {
    if (isAxiosError(error)) {
      ElMessage.error(error.message);
    } else {
      ElMessage.error("网络异常。");
    }
  }
};

// 获取分类名称
const fetchCategoryName = async (categoryId: number) => {
  if (!categoryId) return;

  try {
    const response = await axios.get<ResultContext<string>>(
      "http://localhost:8080/api/categories/name",
      {
        params: { categoryId },
      },
    );
    categoryName.value = response.data.data;
  } catch (_error) {
    ElMessage.error("获取分类名称失败。");
  }
};

// 查询图书借阅状态
async function getBorrowRecord(bookId: number) {
  try {
    const response = await axios.get<ResultContext<BorrowRecord>>(
      "http://localhost:8080/api/borrows",
      {
        params: {
          userId: logging.getUser?.id,
          bookId: bookId,
        },
      },
    );
    borrowRecord.value = response.data.data;
  } catch (_error) {
    ElMessage.error("网络异常。");
  }
}

// 查询图书收藏状态
async function getFavoriteRecord(bookId: number) {
  try {
    const response = await axios.get<ResultContext<FavoriteRecord>>(
      "http://localhost:8080/api/favorites",
      {
        params: {
          userId: logging.getUser?.id,
          bookId: bookId,
        },
      },
    );

    if (response.data.code === 0) {
      favoriteRecord.value = response.data.data;
    }
  } catch (_error) {
    ElMessage.error("网络异常。");
  }
}

// 初始加载
onMounted(async () => {
  const bookId = Number(route.params.id);
  if (!isNaN(bookId)) {
    isLoading.value = true;
    try {
      await fetchBook(bookId);
      if (book.value?.categoryId) {
        void fetchCategoryName(book.value.categoryId);
      }

      // 如果用户已登录，获取借阅和收藏状态
      if (logging.getUser) {
        await Promise.all([getBorrowRecord(bookId), getFavoriteRecord(bookId)]);
      }
    } finally {
      isLoading.value = false;
    }
  }
});

//计算deadline
const deadline = computed(() => {
  const deadline = new Date(now.value);
  deadline.setDate(deadline.getDate() + 30);
  return deadline;
});

//格式化时间
const formattedDeadline = computed(() => {
  return deadline.value.toLocaleDateString("zh-CN");
});

//打开弹窗更新当前时间
function openDialog() {
  now.value = new Date();
  dialogVisible.value = true;
}

function openReturnDialog() {
  now.value = new Date();
  returnDialogVisible.value = true;
}

//借书方法
async function borrowBook() {
  if (!logging.getUser) {
    ElMessage.error("请先登录后再操作。");
    return;
  }
  if (!book.value) {
    ElMessage.error("图书信息未加载，无法借书。");
    return;
  }

  try {
    const response = await axios.post<ResultContext<BorrowRecord>>(
      "http://localhost:8080/api/borrows",
      {
        userId: logging.getUser.id,
        bookId: book.value.id,
      },
    );

    if (response.data.code === 0) {
      // 更新图书的数量
      if (
        book.value?.borrowCount !== null &&
        book.value?.borrowCount !== undefined
      ) {
        book.value.borrowCount++;
        book.value.stock = response.data.data.book.stock;
      }

      // 更新借阅记录
      borrowRecord.value = response.data.data;
      if (logging.getUser) {
        logging.updateBorrowCount(logging.getUser.borrowCount + 1);
      }
      ElMessage.success("借书成功！请按时归还 ~");
    }
  } catch (error) {
    if (isAxiosError(error)) {
      const result = error.response?.data as ResultContext<void>;
      const messages: Partial<Record<BusinessStatusCode, string>> = {
        [BusinessStatusCode.DATABASE_ERROR]: "服务器异常",
        [BusinessStatusCode.USER_NOT_FOUND]: "用户不存在。",
        [BusinessStatusCode.BOOK_NOT_FOUND]: "图书不存在。",
        [BusinessStatusCode.BOOK_OUT_OF_STOCK]: "图书库存不足。",
        [BusinessStatusCode.BORROW_RECORD_STATUS_CONFLICT]:
          "您已经借阅过此书。",
      };
      ElMessage.error(messages[result.code] ?? "操作失败，请稍后尝试。");
    } else {
      ElMessage.error("网络异常。");
    }
  }
  dialogVisible.value = false;
}

//还书方法
async function returnBook() {
  if (!logging.getUser) {
    ElMessage.error("请先登录后再操作。");
    return;
  }

  if (!borrowRecord.value) {
    ElMessage.error("您还未借阅过此图书。");
    return;
  }

  try {
    const response = await axios.patch<ResultContext<BorrowRecord>>(
      `http://localhost:8080/api/borrows/${borrowRecord.value.id}/return`,
    );
    if (response.data.code === 0) {
      if (book.value) {
        book.value.stock = response.data.data.book.stock;
      }
      borrowRecord.value = undefined;
      ElMessage.success("还书成功。");
      returnDialogVisible.value = false;
    }
  } catch (error) {
    if (isAxiosError(error)) {
      const result = error.response?.data as ResultContext<void>;
      const messages: Partial<Record<BusinessStatusCode, string>> = {
        [BusinessStatusCode.DATABASE_ERROR]: "服务器异常",
        [BusinessStatusCode.BORROW_RECORD_NOT_FOUND]: "借阅记录不存在。",
        [BusinessStatusCode.BORROW_RECORD_STATUS_CONFLICT]:
          "您已经归还了此书。",
        [BusinessStatusCode.BOOK_NOT_FOUND]: "图书不存在。",
        [BusinessStatusCode.BOOK_STOCK_OVERFLOW]: "图书数量溢出。",
      };
      ElMessage.error(messages[result.code] ?? "操作失败，请稍后尝试。");
    } else {
      ElMessage.error("网络异常。");
    }
  }
}
//收藏方法
async function favoriteBook() {
  if (!logging.getUser) {
    ElMessage.error("请先登录后再操作。");
    return;
  }

  if (!book.value) {
    ElMessage.error("图书信息未加载，无法收藏。");
    return;
  }

  try {
    const response = await axios.post<ResultContext<FavoriteRecord>>(
      "http://localhost:8080/api/favorites",
      {
        userId: logging.getUser.id,
        bookId: book.value.id,
      },
    );

    if (response.data.code === 0) {
      favoriteRecord.value = response.data.data;

      if (book.value?.favoriteCount) {
        book.value.favoriteCount++;
      }

      if (logging.getUser) {
        logging.updateFavoriteCount(logging.getUser.favoriteCount + 1);
      }
      ElMessage.success("收藏成功！");
    }
  } catch (error) {
    if (isAxiosError(error)) {
      const result = error.response?.data as ResultContext<void>;
      const errorMessages: Record<number, string> = {
        3006: "您已收藏过此书",
      };
      const message =
        (result.code && errorMessages[result.code]) || "操作失败，请稍后尝试。";
      ElMessage.error(message);
    } else {
      ElMessage.error("网络异常。");
    }
  }
}

//取消收藏方法
async function unfavoriteBook() {
  if (!logging.getUser) {
    ElMessage.error("请先登录后再操作。");
    return;
  }

  if (!favoriteRecord.value) {
    ElMessage.error("您还未收藏过此图书。");
    return;
  }

  try {
    await axios.delete(
      `http://localhost:8080/api/favorites/${favoriteRecord.value.id}`,
    );
    favoriteRecord.value = undefined;

    if (book.value?.favoriteCount) {
      book.value.favoriteCount--;
    }

    if (logging.getUser) {
      logging.updateFavoriteCount(logging.getUser.favoriteCount - 1);
    }
    ElMessage.success("取消收藏成功！");
  } catch (error) {
    if (isAxiosError(error)) {
      ElMessage.error("操作失败，请稍后尝试。");
    } else {
      ElMessage.error("网络异常。");
    }
  }
}

const isBorrowed = computed(() => {
  return !!borrowRecord.value;
});

const isFavorited = computed(() => {
  return !!favoriteRecord.value;
});

const isLoggedIn = computed(() => {
  return !!logging.getUser;
});

function formatParagraph(text: string): string {
  if (!text) return "";
  return text
    .replace(/\r\n?/g, "\n") // 替换 \r 或 \r\n 为 \n
    .split("\n")
    .map(line => `<p>${line}</p>`)
    .join("");
}
</script>

<template>
  <div class="content">
    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-container">
      <el-loading
        element-loading-text="加载中..."
        element-loading-background="rgba(0, 0, 0, 0.8)"
      />
    </div>

    <!-- 主要内容 -->
    <template v-else-if="book">
      <div class="breadcrumb">
        <el-breadcrumb :separator-icon="ArrowRight" style="font-size: 18px">
          <el-breadcrumb-item :to="{ path: '/' }">
            <span style="color: #606266; font-weight: lighter">首页</span>
          </el-breadcrumb-item>
          <el-breadcrumb-item
            :to="{ path: '/category', query: { categoryId: book?.categoryId } }"
          >
            <span style="color: #606266; font-weight: lighter">{{
              categoryName
            }}</span>
          </el-breadcrumb-item>
          <el-breadcrumb-item>
            <span style="color: black">{{ book?.title }}</span>
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="book">
        <div class="img">
          <img :src="`/img/${book.img}`" />
        </div>
        <div class="book-info">
          <div class="title">
            {{ book?.title }}
          </div>
          <div class="author">作者：{{ book?.author }}</div>
          <div class="isbn">
            国际标准书号：<span>{{ book?.isbn }}</span>
          </div>
          <div class="book-stats">
            <div class="total">
              馆藏 <span>{{ book?.total }}</span> 本
            </div>
            <div class="stock">
              在馆 <span>{{ book?.stock }}</span> 本
            </div>
            <div class="borrowing">
              <span>{{ book?.borrowCount }}</span> 总借阅
            </div>
            <div class="favorite">
              <span>{{ book?.favoriteCount }}</span> 总收藏
            </div>
          </div>
          <div class="buttons">
            <!-- 借书/还书按钮 - 互斥显示 -->
            <template v-if="isLoggedIn">
              <el-button
                v-if="!isBorrowed"
                class="borrow"
                @click="openDialog"
                :disabled="!book?.stock || book.stock <= 0"
              >
                {{ !book?.stock || book.stock <= 0 ? "库存不足" : "借书" }}
              </el-button>
              <el-button v-else class="return" @click="openReturnDialog">
                还书
              </el-button>
            </template>
            <el-button v-else class="login-required" disabled>
              请先登录
            </el-button>

            <!-- 借书确认对话框 -->
            <el-dialog
              v-model="dialogVisible"
              title="确认借书"
              width="500px"
              align-center
            >
              <span
                >如果在<b>{{ formattedDeadline }}</b
                >前不归还，则视为逾期。</span
              >
              <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="borrowBook">确定</el-button>
              </template>
            </el-dialog>

            <!-- 还书确认对话框 -->
            <el-dialog
              v-model="returnDialogVisible"
              title="确认还书"
              width="500px"
              align-center
            >
              <span>确认归还此书？</span>
              <template #footer>
                <el-button @click="returnDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="returnBook">确定</el-button>
              </template>
            </el-dialog>

            <!-- 收藏/取消收藏按钮 - 互斥显示 -->
            <template v-if="isLoggedIn">
              <button v-if="!isFavorited" class="like" @click="favoriteBook()">
                收藏
              </button>
              <button v-else class="unlike" @click="unfavoriteBook()">
                取消收藏
              </button>
            </template>
          </div>
        </div>
      </div>
      <div class="detail">
        <div class="title">
          <span>作品简介</span>
        </div>
        <div
          class="description"
          v-html="formatParagraph(book?.description)"
        ></div>
      </div>
    </template>

    <!-- 错误状态 -->
    <div v-else class="error-container">
      <el-empty description="图书信息加载失败" />
    </div>
  </div>
</template>

<style scoped>
.content {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
  background: #f8f9fa;
  min-height: 100vh;
}

.breadcrumb {
  margin-bottom: 32px;
  padding: 16px 24px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.book {
  background: white;
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  margin-bottom: 32px;
  display: flex;
  gap: 32px;
  align-items: flex-start;
  transition: box-shadow 0.3s ease;
}

.book:hover {
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
}

.img {
  flex-shrink: 0;
  width: 250px;
}

.book-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.book-stats {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 4px 12px;
  margin: 12px 0;
}

.img img {
  width: 100%;
  height: auto;
  max-height: 400px;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.title {
  font-size: 28px;
  font-weight: 700;
  color: #333;
  margin-bottom: 12px;
  line-height: 1.3;
  border-bottom: 3px solid #67c23a;
  padding-bottom: 8px;
}

.author {
  font-size: 18px;
  color: #666;
  margin-bottom: 16px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.isbn,
.total,
.stock,
.borrowing,
.favorite {
  font-size: 16px;
  color: #666;
  margin-bottom: 8px;
  padding: 4px 0;
  display: inline-block;
  white-space: nowrap;
}

.isbn span,
.total span,
.stock span,
.borrowing span,
.favorite span {
  font-weight: 700;
  font-size: 18px;
  color: #333;
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin: 0 4px;
}

.book button {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-right: 12px;
  margin-top: 16px;
  min-width: 100px;
}

.borrow {
  width: 100px;
  height: 45px;
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
  margin-bottom: 20px;
}

.borrow:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(103, 194, 58, 0.4);
}

.return {
  width: 100px;
  height: 45px;
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  margin-bottom: 20px;
}

.return:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(64, 158, 255, 0.4);
}

.like {
  background: linear-gradient(135deg, #f56c6c 0%, #ff8a8a 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);
}

.like:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(245, 108, 108, 0.4);
}

.unlike {
  background: linear-gradient(135deg, #a3a3c2 0%, #cfcfe6 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(144, 147, 153, 0.3);
}

.unlike:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(144, 147, 153, 0.4);
}

.login-required {
  background: linear-gradient(135deg, #c0c4cc 0%, #d3d4d6 100%);
  color: #909399;
  cursor: not-allowed;
}

.loading-container {
  min-height: 400px;
  position: relative;
}

.error-container {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.detail {
  background: white;
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: box-shadow 0.3s ease;
}

.detail:hover {
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
}

.detail .title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 2px solid #67c23a;
}

.detail .title span {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.description {
  font-size: 16px;
  line-height: 1.8;
  color: #555;
  text-align: justify;
  text-indent: 2em;
  letter-spacing: 0.5px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .book {
    gap: 24px;
  }

  .img {
    width: 200px;
  }

  .title {
    font-size: 24px;
  }
}

@media (max-width: 768px) {
  .content {
    padding: 16px;
  }

  .book {
    flex-direction: column;
    gap: 20px;
    padding: 24px;
  }

  .img {
    width: auto;
    text-align: center;
  }

  .img img {
    max-width: 250px;
  }

  .title {
    font-size: 22px;
  }

  .book-stats {
    grid-template-columns: 1fr;
    gap: 4px;
  }

  .book button {
    width: 100%;
    margin-right: 0;
    margin-bottom: 8px;
  }

  .detail {
    padding: 24px;
  }
}

@media (max-width: 480px) {
  .breadcrumb {
    padding: 12px 16px;
  }

  .book {
    padding: 20px;
  }

  .detail {
    padding: 20px;
  }

  .title {
    font-size: 20px;
  }

  .detail .title {
    font-size: 20px;
  }
}
</style>
